package com.gitee.sidihuo.sse.other;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 非sse的okhttp3常规请求（入参是表单非json）
 */
@Slf4j
public class OkHttpNoSseFormBodyPoster {

    public static String post(Map<String, String> formBodyMap, String url, Map<String, String> headers) throws IOException {
        return post(formBodyMap, url, headers, 100);
    }

    public static String post(Map<String, String> formBodyMap, String url, Map<String, String> headers, int timeoutSeconds) throws IOException {
        return post(formBodyMap, url, headers, timeoutSeconds, true, true);
    }

    public static String post(Map<String, String> formBodyMap, String url, Map<String, String> headers, int timeoutSeconds, boolean logReq, boolean logRes) throws IOException {
        formBodyMap = formBodyMap == null ? new HashMap<>() : formBodyMap;
        String requestJson = JSONObject.toJSONString(formBodyMap);
        FormBody.Builder builderFormBody = new FormBody.Builder();
        for (Map.Entry<String, String> entry : formBodyMap.entrySet()) {
            builderFormBody.add(entry.getKey(), entry.getValue());
        }
        FormBody formBody = builderFormBody.build();
        headers = headers == null ? new HashMap<>() : headers;
        long currentTimeMillis = System.currentTimeMillis();
        log.info("OkHttpNoSseFormBodyPoster post begin url = {} jsonForm = {} currentTimeMillis = {}", url, logReq ? requestJson : "log not enabled", currentTimeMillis);
        Request.Builder builder = new Request.Builder()
                .url(url)
                .headers(Headers.of(headers))
                .method("POST", formBody);
        log.info("OkHttpNoSseFormBodyPoster add post header {}", JSONObject.toJSONString(headers));

        Request request = builder.build();
        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(100, TimeUnit.SECONDS)
                .readTimeout(timeoutSeconds, TimeUnit.SECONDS)
                .build();
        try (Response response = client.newCall(request).execute()) {
            long currentTimeMillisEnd = System.currentTimeMillis();
            long timeConsuming = currentTimeMillisEnd - currentTimeMillis;
            log.info("OkHttpNoSseFormBodyPoster post end url {} response {} {} timeConsuming = {}", url, response.code(), response.message(), timeConsuming);
            if (200 != response.code()) {
                log.warn("OkHttpNoSseFormBodyPoster post end url {} response code = {} {}", url, response.code(), currentTimeMillis);
                throw new RuntimeException("OkHttpNoSsePoster post response code = " + response.code());
            }
            ResponseBody responseBody = response.body();
            if (responseBody == null) {
                log.warn("OkHttpNoSseFormBodyPoster post responseBody is null {}", currentTimeMillis);
                return null;
            }
            String responseString = responseBody.string();
            log.info("OkHttpNoSseFormBodyPoster post end url {} responseString {} {}", url, logRes ? responseString : "log not enabled", currentTimeMillis);
            return responseString;
        } catch (IOException e) {
            log.warn("OkHttpNoSseFormBodyPoster IOException");
            throw e;
        }
    }

}
